package com.baihan.angus.app.game.busshow.ui.main.log_in;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.alibaba.android.arouter.launcher.ARouter;
import com.baihan.angus.app.game.basic.BaseApplication;
import com.baihan.angus.app.game.basic.base.view_model.BaseViewModel;
import com.baihan.angus.app.game.basic.bindingAdp.view_click.ClickEvent;
import com.baihan.angus.app.game.basic.utils.GenerateTestUserSig;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.basic.utils.net.ApiObserver;
import com.baihan.angus.app.game.basic.utils.regex.RegexUtils;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.common.arouter_path.ArouterAppPath;
import com.baihan.angus.app.game.common.bean.response.LoginResponse;
import com.baihan.angus.app.game.common.bean.response.SmsCodeResponse;
import com.baihan.angus.app.game.common.configs.UserConfig;
import com.baihan.angus.app.game.common.constants.CommonVariable;
import com.baihan.angus.app.game.common.data_center.remote.RemoteDataMng;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.baihan.angus.app.game.common.constants.BasicConstants.MOBILE_LOGIN;

public class LoginVM extends BaseViewModel {

    private Map<String, Object> mCodeRequest = new HashMap<>();
    private Map<String, Object> mLoginRequest = new HashMap<>();

    private int userType;//0-玩家 1-主持人

    public LoginVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<Boolean> ofAgreePrivacy = new ObservableField<>(Boolean.FALSE);
    public ObservableField<String> ofPhone = new ObservableField<String>();
    public ObservableField<String> ofCode = new ObservableField<String>();
    public ObservableField<String> ofGetCode = new ObservableField<>();
    public ObservableField<Boolean> ofCodeEnable = new ObservableField<>(Boolean.TRUE);

    public void setUserType(int userType) {
        this.userType = userType;
    }

    public ClickEvent clickGetCode = new ClickEvent() {
        @Override
        public void onClick(View view) {
            if (TextUtils.isEmpty(ofPhone.get())) {
                Tooast.normalInfo(BaseApplication.getApplication().getString(R.string.inputPhoneNum));
            } else {
                if (RegexUtils.isMobileSimple(ofPhone.get())) {
                    mCodeRequest.put("mobile", ofPhone.get().trim());
                    mCodeRequest.put("event", MOBILE_LOGIN);

                    codeTimeLimit();
                    getCode(mCodeRequest);
                } else {
                    Tooast.normalInfo(BaseApplication.getApplication().getString(R.string.phoneIsWrong));
                }
            }
        }
    };

    public void getCode(Map<String, Object> pMap) {
        ofCodeEnable.set(false);
        RemoteDataMng.getInstance().getSmsCode(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<SmsCodeResponse>() {
            @Override
            public void onSuccess(SmsCodeResponse smsCodeResponse) {
//                Tooast.normalInfo(getApplication().getString(R.string.veriCodeIsSend));
                Tooast.normalInfo("验证码："  + smsCodeResponse.getData().getCode());
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
                ofCodeEnable.set(true);
            }
        });
    }

    public ClickEvent clickLogin = new ClickEvent() {
        @Override
        public void onClick(View view) {
            if (ofAgreePrivacy.get()) {
                if (TextUtils.isEmpty(ofPhone.get())) {
                    Tooast.normalInfo(BaseApplication.getApplication().getString(R.string.inputPhoneNum));
                } else if (TextUtils.isEmpty(ofCode.get())) {
                    Tooast.normalInfo(BaseApplication.getApplication().getString(R.string.inputCode));
                } else {
                    mLoginRequest.put("mobile", ofPhone.get());
                    mLoginRequest.put("captcha", ofCode.get());
                    mLoginRequest.put("type", userType);
                    codeLogin(mLoginRequest);
                }
            } else {
                Tooast.normalInfo(BaseApplication.getApplication().getString(R.string.readAgreePrivacy));
            }
        }
    };

    public void codeLogin(Map<String, Object> pMap) {
        showLoading("codeLogin");
        RemoteDataMng.getInstance().codeLogin(pMap, mLifecycleProvider.bindToLifecycle(), new ApiObserver<LoginResponse>() {
            @Override
            public void onSuccess(LoginResponse loginResponse) {
                hideLoading("codeLogin");
                UserConfig.getUserConfig().saveUser(loginResponse.getData().getUserinfo());
                UserConfig.getUserConfig().saveUserSig(GenerateTestUserSig.genTestUserSig(loginResponse.getData().getUserinfo().getId()));
                UserConfig.getUserConfig().saveAppToken(loginResponse.getData().getUserinfo().getToken());
                ARouter.getInstance().build(ArouterAppPath.MAIN_ACTIVITY).navigation();
                finish();
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("codeLogin");
                Tooast.warning(msg);
            }
        });
    }

    private Disposable mDisposable;

    public long timeLimit = 60;

    public void codeTimeLimit() {
        Observable.interval(0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
                if (timeLimit == 60) {
                    CommonVariable.REGISTER_TIME = System.currentTimeMillis() + 60 * 1000;
                }
            }

            @Override
            public void onNext(Long aLong) {

                long a = timeLimit - aLong;
                if (a > 0) {
                    ofGetCode.set(a + "s后再次发送");
                } else {
                    timeLimit = 60;
                    ofGetCode.set(getApplication().getString(R.string.getVerifyCode));
                    ofCodeEnable.set(true);
                    stopDispose();
                }
            }

            @Override
            public void onError(Throwable e) {
                timeLimit = 60;
                ofGetCode.set(BaseApplication.getApplication().getString(R.string.getVerifyCode));
                ofCodeEnable.set(true);
                stopDispose();
            }

            @Override
            public void onComplete() {
                timeLimit = 60;
                ofGetCode.set(BaseApplication.getApplication().getString(R.string.getVerifyCode));
                ofCodeEnable.set(true);
                stopDispose();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopDispose();
    }

    private void stopDispose() {
        if (mDisposable != null) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
